package cn.hls.web.controller.dict;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hls.entity.Module;
import cn.hls.entity.vo.ExtTree;
import cn.hls.entity.vo.Msg;
import cn.hls.entity.vo.PageInfo;
import cn.hls.service.ModuleService;
import cn.hls.web.controller.base.BaseController;

/**
 * @fileName: ModuleController.java
 * @Description: 模块Controller类
 * @author: yinghui.zhang
 * @email: uuhui@163.com
 * @date 2015年4月15日
 * @version V1.0
 */
@Controller
@RequestMapping("/module")
public class ModuleController extends BaseController<Module> {
	@Resource(name = "moduleService")
	private ModuleService moduleService;

	@RequestMapping("/add")
	@ResponseBody
	public Msg add(Module entity) throws Exception {
		Module module = moduleService.findModule(entity);
		if (module != null) {// 对象存在
			msg.setStatus(201);
			msg.setInfo("模块名称或模块代码已经存在");
		} else {
			boolean flag = moduleService.add(entity);
			if (!flag) {
				msg.setStatus(202);
				msg.setInfo("操作失败");
			}else{
				msg.setInfo("操作成功");
				msg.setStatus(200);
			}
		}
		return msg;
	}

	@RequestMapping("/update")
	@ResponseBody
	public Msg update(Module entity) throws Exception {
		if (entity.getParent().getId() == null)
			entity.setParent(null);
		else
			entity.setParent(moduleService.find(entity.getParent().getId()));
		if (entity.getUpdateTime() == null) {
			entity.setUpdateTime(new Date());
		}
		boolean flag = moduleService.update(entity);
		if (!flag) {
			msg.setStatus(201);
			msg.setInfo("操作失败");
		}else{
			msg.setStatus(200);
			msg.setInfo("操作成功");
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping("/del")
	public Msg del(Long id) throws Exception {
		String result = moduleService.deleteModule(id);
		if (!result.equalsIgnoreCase("ok")) {
			msg.setStatus(201);
			msg.setInfo("删除失败,原因："+result);
		}else{
			msg.setInfo("删除成功!");
			msg.setStatus(200);
		}
		return msg;
	}

	// 排序
	@ResponseBody
	@RequestMapping("/sort")
	public Msg sort(String ids) throws Exception {
		try {
			moduleService.updateModuleSort(ids);
			return msg;
		} catch (Exception e) {
			throw e;
		}
	}

	@RequestMapping("/view")
	public String view(Model model) {
		return "dict/module";
	}

	@RequestMapping("/list")
	@ResponseBody
	public PageInfo<Module> list(Module entity, PageInfo<Module> page) throws Exception {
		return moduleService.loadModules(entity, page);
	}

	@ResponseBody
	@RequestMapping("/tree")
	public List<ExtTree> tree(Module entity, Long nodeId) throws Exception {
		return moduleService.loadChildModules(entity, nodeId == null || nodeId == 0 ? null : nodeId);
	}


}
